import { CellStyle, ElMessage,ElMessageBox, ElLoading  } from 'element-plus';
import { ref, reactive, getCurrentInstance, ComponentInternalInstance, nextTick } from 'vue';
import { useOptionData} from '/@/stores/optionData';
export function useList(obj:any){
  const {pageApi, deleteApi, searchFixed} = obj;
  const {proxy} :any = getCurrentInstance() as ComponentInternalInstance;

  let primaryKey:string = obj.primaryKey ? obj.primaryKey : 'id'; // 主键
  let resKey:string = obj.resKey; // 列表放回的数据键
  let searchParams = reactive({}); // 搜索参数
  let tableData = reactive({
    pageApi: pageApi,
    loading: true,// 加载
    list: [],// 表格数据
    checkedList: [],// 多选的列表
    checkedIds: [],// 多选的id集合
    initIds: [], // 初始化
    radioObj: {}, //选中的列
    radioId: null,// 选中的id
    cellStyle: { textAlign: 'center' },
		headerCellStyle: {
			// textAlign: 'center',
			background: 'var(--el-table-row-hover-bg-color)',
			color: 'var(--el-text-color-primary)',
		},
  });
  let pageData = reactive({
    page: 1,
    size: 10,
    pageSizes: [10,15,30,50,100],
    total: 0
  });
  let dlgAddEdit = reactive({
    type: 'add',
    row: {},
  });
  const optionDataStore = useOptionData();
  // const optionData = reactive({});
  // 获取列表数据
  const getList = (page:number = 1) => {
    let params = {
      page: page,
      current: page,
      size: pageData.size
    };
    params = Object.assign({},params,searchParams, {shopId: localStorage.getItem('shopId') == '0' ? null : localStorage.getItem('shopId')}, searchFixed);
    tableData.loading = true;
    return new Promise((resolve, reject) => {
      proxy.$request('get', tableData.pageApi, params, (data:any,msg:any) => {
        if(resKey == 'data'){
          tableData.list = data;
          console.log(data);
        }else{
          tableData.list = data.records;
          pageData.total = data.total;
          pageData.page = data.current;
          pageData.current = data.current;
        }
        
        tableData.loading = false;
        resolve(data.records);
      })
    })    
  };
  // 搜索
  const handleSearch = (opt:object) => {
    searchParams = opt;
    return new Promise((resolve, reject) => {
      getList().then(res => {
        resolve(res);
      })
    });    
  };
  // 分页条数切换
  const sizeChange = (val:number) => {
    pageData.size = val;
    getList(pageData.page);
  };
  // 设置初始化的选中状态,TODO
  const setDefaultCheckbox = (target:any) => {
    let data = tableData;
      nextTick( ()=> {
        data.list.forEach((item,i) => {
          if(data.initIds.indexOf(item[primaryKey]) != -1){
            target.value.toggleRowSelection(data.list[i],true);
          }
        }) 
      })
  };
  // 列的多选操作
  const selectCheckbox = (val:any) => {
    tableData.checkedList = val;
    tableData.checkedIds = val.map((item:any) => {
      return item[primaryKey];
    });
  };
  // 列的单选操作
  const selectRadio = (row:any) => {
    tableData.radioObj = row;
    tableData.radioId = row[primaryKey];
  };
  const handleOperate = (target:any, row:any, type?:string) => {    
    if(type == 'edit'){
      target.init(type, row);
      dlgAddEdit.type = type;
      dlgAddEdit.row = row;
    }else if(type == 'add'){
      target.init(type,row);
    }else{
      target.init(row);
    } 
    
  };
  const handleDelete = (val:any) => {
    console.log(val);
    let type:string = '个';
    if(Array.isArray(val)){
      type = '些'
      if(val.length == 0){
        ElMessage.warning('请先选择！');
        return;
      }
    };  
    ElMessageBox.confirm(
      '确定要删除这' + type + '数据?', 
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
          proxy.$request('delete', deleteApi, (data:any, msg:any) => {
            ElMessage.success('删除成功！');
            getList(pageData.page);
          })          
    })
  };
  const handleDeleteMultiple = (val:array) => {
    let type:string = '个';
    if(val.length == 0){
      ElMessage.warning('请先选择！');
      return;
    }else if(val.length > 1){
      type = '些'      
    };  
    ElMessageBox.confirm(
      '确定要删除这' + type + '数据?', 
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
          proxy.$request('delete', deleteApi, val, (data:any, msg:any) => {
            ElMessage.success('删除成功！');
            getList(pageData.page);
          })          
    })
  };
  
  /** 导出 */
	const handleExport = (title:string, api:string, params:any = {}, methods:string) => {
		ElMessageBox.confirm('是否确认导出所有'+title+'数据项?', {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning"
			}).then(() => {
				const loading = ElLoading.service({
          lock: true,
          text: '下载中，请稍等',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      let m = methods || 'get';
			proxy.$request(m, api, params, (data:any, msg:any)=>{
				loading.close();
				download(data,title);        
			},(msg:any) => {
				loading.close();
			}, {responseType: 'blob'}, 'all');
		}).catch((action) => {
			
		});
	};
	const download = (data:any,title:string) => {
		let url = window.URL.createObjectURL(
			new Blob([data], { type: "application/vnd.ms-excel" })
		);
		let link = document.createElement("a");
		link.style.display = "none";
		link.href = url;
		link.setAttribute("download", title +".xlsx");
		document.body.appendChild(link);
		link.click();
	};
  return{
    searchParams,
    tableData,
    pageData,
    dlgAddEdit,
    optionDataStore,
    getList,
    handleSearch,
    sizeChange,
    setDefaultCheckbox,
    selectCheckbox,
    selectRadio,
    handleOperate,
    handleDelete,
    handleDeleteMultiple,
    handleExport,
  }
}